package DBLayer;

import java.sql.*;
import java.util.ArrayList;

import ModelLayer.*;

public class DbIncomingOrder {
	
private  Connection con;
	
	public DbIncomingOrder()
	{
		//Constructer of DbIncomingOrder where the connection is being initialized.
		con = DbConnection.getInstance().getDBcon();
	}
	

	public IncomingOrder findOrder(String orderId) {
		//Finds an IncomingOrder by calling the singleWhere-method using the my using the orderId as wClause
		String wClause = "  orderId = '" + orderId + "'";
        return singleWhere(wClause);
	}

	public int insertOrder(IncomingOrder iO) throws Exception {
		//Inserts an IncomingOrder-row by creating a query with the IncomingOrder-object
		int nextOrderId = GetMax.getMaxId("Select max(orderId) from IncomingOrder");
        nextOrderId = nextOrderId + 1;
        System.out.println("next orderId = " +  nextOrderId);
  
       int rc = -1;
	   String queryOrder="INSERT INTO IncomingOrder(orderId)  VALUES('"+
			   nextOrderId  + "','"  +
			   iO.getC().getCustomerId()  + "','"  +
			   iO.getDate()  + "','"  +
			   iO.getOrderStatus()  + "','"  +
			   iO.getDateSent()  + "')";
	   
	   try{
	    	  System.out.println("insert : " + queryOrder);
	          Statement stmt = con.createStatement();
	          stmt.setQueryTimeout(5);
	     	  rc = stmt.executeUpdate(queryOrder);
	          stmt.close();
	      }
	       catch(SQLException ex){
	          System.out.println("IncomingOrder is not inserted correct");
	          throw new Exception ("IncomingOrder is not inserted correct");
	       }
      
       return(rc);
	}

	public int updateOrder(IncomingOrder oObj, String orderId) {
		// Updates the order-row by creating a query, using the Incomingorder object and the orderId.
		IncomingOrder iO = oObj;
		int rc = -1;
		
		String query="UPDATE IncomingOrder SET "+
			 	  "orderStatus ='"+ iO.getOrderStatus() + "', " +
	              "dateSent ='"+ iO.getDateSent() + "'" +
			          " WHERE orderId = '"+ orderId + "'";
	                System.out.println("Update query:" + query);
	  		try{ 
		 		Statement stmt = con.createStatement();
		 		stmt.setQueryTimeout(5);
		 	 	rc = stmt.executeUpdate(query);

		 	 	stmt.close();
			}
		 	catch(Exception ex){
		 	 	System.out.println("Update exception in IncomingOrder db: "+ex);
		  	}
			return(rc);
	}
	
	public int delete(int orderId) {
		//Delete a row, by using the orderId.
		int rc=-1;
		  
	 	String queryOrder="DELETE FROM IncomingOrder WHERE orderId = '" +
				orderId + "'";
                System.out.println(queryOrder);
	  	try{ 
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	rc = stmt.executeUpdate(queryOrder);
	 	  	stmt.close();
  		}
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in IncomingOrder db: "+ex);
   	        }
	  	
		return(rc);
	}

	private IncomingOrder singleWhere(String wClause)
	{
		//Creates a single order by calling the buildQuery and then the buildOrder()-method
		ResultSet results;
		IncomingOrder iO = new IncomingOrder();
                
	        String query =  buildQuery(wClause);
                System.out.println(query);
		try{
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
                            iO = buildOrder(results);
                            
                            stmt.close();
			}
                        else{ 
                            iO = null;
                        }
		}	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return iO;
	}
	
	private ArrayList<IncomingOrder> miscWhere(String wClause)
	{
		//Creates several orders by calling the buildQuery and then the buildOrder()-method
        ResultSet results;
	    ArrayList<IncomingOrder> list = new ArrayList<IncomingOrder>();	
		
	    String query =  buildQuery(wClause);
  
            try{
		Statement stmt = con.createStatement();
	 	stmt.setQueryTimeout(5);
	 	results = stmt.executeQuery(query);
	 	
	
		while( results.next() ){
	     	 IncomingOrder iO = new IncomingOrder();
	     	 iO = buildOrder(results);	
             list.add(iO);	
		}
                 stmt.close();		
		}
	 	catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return list;
	}	
	
	private String buildQuery(String wClause)
	{
		//Builds the query, by using the wClause
	    String query="SELECT orderId, customerId, date, orderStatus, dateSent FROM IncomingOrder";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	
	private IncomingOrder buildOrder(ResultSet results)
    {   
		//Builds an order by using the results.
		IncomingOrder iO = new IncomingOrder();
        try{
        	  iO.setOrderId(results.getString("orderId"));
        	  iO.setC(new Customer(Integer.parseInt(results.getString("customerId"))));
        	  iO.setDate(results.getString("date"));
        	  iO.setOrderStatus(results.getString("orderStatus"));
        	  iO.setDateSent(results.getString("dateSent"));
        }
       catch(Exception e)
       {
           System.out.println("error in building the incomingOrder object");
       }
       return iO;
    }
	
	
	
	
	public ArrayList<IncomingOrder>  getAllOrders() {
		//Returns a list with all orders. Makes use of the buildOrder-method.
		ResultSet results;
	    ArrayList<IncomingOrder> list = new ArrayList<IncomingOrder>();	
		
	    String query =  "SELECT orderId, customerId, date, orderStatus, dateSent FROM IncomingOrder";
	    System.out.println(query);
  
        try {
			Statement stmt = con.createStatement();
		 	stmt.setQueryTimeout(5);
		 	results = stmt.executeQuery(query);
	 	
	
			while(results.next()) {
				IncomingOrder obj;
		     	 obj = buildOrder(results);	
                 list.add(obj);	
			}
			stmt.close();
		}
	 	catch(Exception e) {
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return list;
	}
}